<?php
/**
 * Created by PhpStorm.
 * User: dt
 * Date: 2017/9/19
 * Time: 10:50
 */

namespace frontend\models;

use Yii;
use frontend\base\BModel;
use frontend\utils\AliyunSms\Sms;
use yii\base\UserException;

class SmsCodeModel extends BModel
{
    public static function tableName()
    {
        return 'sms_code';
    }

    public function rules()
    {
        return [
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'id',
            'phone' => '手机号',
            'sms_code' => '短信验证码',
            'send_ip' => '发送方ip',
            'create_time' => '创建时间',
        ];
    }

    /***
     *短信发送
     * @param $mobile $type $type $data
     * @return array
     * SmsCodeModel::sendSmsMessage('15888893748','validate_code',['name'=>'张三']);
     */
    public static function sendSmsMessage($mobile,$type='validate_code',$data=[])
    {
        $template = Yii::$app->params['sms']['template'][$type];
        $new_template = [];
        $out_id = time().mt_rand(10000,99999);
        if($data) {
            foreach ($data as $key=>$val){
                if(isset($template[$key]) && $key!= 'template_code'){
                    $new_template[$key]=$val;
                }
            }
        }
        $demo = new Sms(
            Yii::$app->params['sms']['key'],
            Yii::$app->params['sms']['secret']
        );
        $response = $demo->sendSms(
            Yii::$app->params['sms']['sign_name'], // 短信签名
            $template['template_code'], // 短信模板编号
            $mobile, // 短信接收者
            $new_template,
            $out_id
        );
        return ['code'=>$response->Code,'message'=>$response->Message,'biz_id'=>!empty($response->BizId) ? $response->BizId : ''];
    }

}